<template>
  <div class="order-exception">
    <!-- 异常统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总异常数</span>
            </div>
          </template>
          <div class="statistics-value">{{ statistics.totalCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待处理</span>
            </div>
          </template>
          <div class="statistics-value warning">{{ statistics.pendingCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>处理中</span>
            </div>
          </template>
          <div class="statistics-value primary">{{ statistics.processingCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已处理</span>
            </div>
          </template>
          <div class="statistics-value success">{{ statistics.resolvedCount }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="异常类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="支付异常" value="payment" />
            <el-option label="发货异常" value="shipping" />
            <el-option label="退款异常" value="refund" />
            <el-option label="服务异常" value="service" />
            <el-option label="其他异常" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="resolved" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleExport">导出异常</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 异常列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="orderNo" label="订单编号" min-width="180" />
        <el-table-column prop="type" label="异常类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.type)">
              {{ getExceptionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="异常描述" min-width="300" show-overflow-tooltip />
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="异常时间" width="180" />
        <el-table-column prop="handler" label="处理人" width="120" />
        <el-table-column prop="handleTime" label="处理时间" width="180" />
        <el-table-column prop="solution" label="处理方案" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="success"
              link
              @click="handleProcess(row)"
            >
              处理
            </el-button>
            <el-button
              v-if="['pending', 'processing'].includes(row.status)"
              type="danger"
              link
              @click="handleClose(row)"
            >
              关闭
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 异常详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="异常详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ detailDialog.data.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="异常类型">
          <el-tag :type="getExceptionTypeTag(detailDialog.data.type)">
            {{ getExceptionTypeLabel(detailDialog.data.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="异常描述" :span="2">
          {{ detailDialog.data.description }}
        </el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getStatusTag(detailDialog.data.status)">
            {{ getStatusLabel(detailDialog.data.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="异常时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="处理人">{{ detailDialog.data.handler || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ detailDialog.data.handleTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理方案" :span="2">{{ detailDialog.data.solution || '-' }}</el-descriptions-item>
      </el-descriptions>

      <div v-if="detailDialog.data.logs?.length" class="exception-logs">
        <div class="logs-title">处理记录</div>
        <el-timeline>
          <el-timeline-item
            v-for="(log, index) in detailDialog.data.logs"
            :key="index"
            :type="getLogTypeTag(log.type)"
            :timestamp="log.createTime"
          >
            {{ log.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 处理异常对话框 -->
    <el-dialog
      v-model="processDialog.visible"
      :title="processDialog.isClose ? '关闭异常' : '处理异常'"
      width="500px"
    >
      <el-form
        ref="processFormRef"
        :model="processDialog.form"
        :rules="processDialog.rules"
        label-width="80px"
      >
        <el-form-item label="处理方案" prop="solution">
          <el-input
            v-model="processDialog.form.solution"
            type="textarea"
            :rows="4"
            :placeholder="processDialog.isClose ? '请输入关闭原因' : '请输入处理方案'"
          />
        </el-form-item>
        <el-form-item label="处理状态" prop="status" v-if="!processDialog.isClose">
          <el-select v-model="processDialog.form.status" placeholder="请选择状态">
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="resolved" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getMerchantOrderExceptions,
  getMerchantOrderExceptionDetail,
  processMerchantOrderException,
  closeMerchantOrderException,
  getMerchantOrderExceptionStatistics,
  exportMerchantOrderExceptions
} from '@/api/merchant'

// 统计数据
const statistics = reactive({
  totalCount: 0,
  pendingCount: 0,
  processingCount: 0,
  resolvedCount: 0
})

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  type: '',
  status: '',
  dateRange: []
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: {}
})

// 处理对话框
const processDialog = reactive({
  visible: false,
  isClose: false,
  id: '',
  form: {
    solution: '',
    status: 'processing'
  },
  rules: {
    solution: [
      { required: true, message: '请输入处理方案', trigger: 'blur' },
      { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择处理状态', trigger: 'change' }
    ]
  }
})

const processFormRef = ref(null)

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantOrderExceptionStatistics()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取异常统计数据失败:', error)
  }
}

// 获取异常列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderExceptions({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    })
    tableData.value = data.list
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取异常列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 导出异常
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    const response = await exportMerchantOrderExceptions(params)
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `订单异常列表_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    ElMessage.error('导出异常失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const { data } = await getMerchantOrderExceptionDetail(row.id)
    detailDialog.data = data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取异常详情失败:', error)
  }
}

// 处理异常
const handleProcess = (row) => {
  processDialog.isClose = false
  processDialog.id = row.id
  processDialog.form = {
    solution: '',
    status: 'processing'
  }
  processDialog.visible = true
}

// 关闭异常
const handleClose = (row) => {
  processDialog.isClose = true
  processDialog.id = row.id
  processDialog.form = {
    solution: ''
  }
  processDialog.visible = true
}

// 提交处理
const submitProcess = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    if (processDialog.isClose) {
      await closeMerchantOrderException(processDialog.id, {
        reason: processDialog.form.solution
      })
      ElMessage.success('关闭异常成功')
    } else {
      await processMerchantOrderException(processDialog.id, processDialog.form)
      ElMessage.success('处理异常成功')
    }
    processDialog.visible = false
    getList()
    getStatistics()
  } catch (error) {
    console.error('提交处理失败:', error)
  }
}

// 获取异常类型标签类型
const getExceptionTypeTag = (type) => {
  const typeMap = {
    payment: 'danger',
    shipping: 'warning',
    refund: 'info',
    service: 'primary',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取异常类型标签文本
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    payment: '支付异常',
    shipping: '发货异常',
    refund: '退款异常',
    service: '服务异常',
    other: '其他异常'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    resolved: 'success',
    closed: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已处理',
    closed: '已关闭'
  }
  return statusMap[status] || status
}

// 获取日志类型标签类型
const getLogTypeTag = (type) => {
  const typeMap = {
    create: 'primary',
    process: 'success',
    close: 'info'
  }
  return typeMap[type] || 'info'
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getStatistics()
  getList()
})
</script>

<style lang="scss" scoped>
.order-exception {
  .statistics-cards {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .statistics-value {
      font-size: 24px;
      font-weight: bold;
      text-align: center;
      
      &.warning {
        color: #E6A23C;
      }
      
      &.primary {
        color: #409EFF;
      }
      
      &.success {
        color: #67C23A;
      }
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .exception-logs {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #EBEEF5;
    
    .logs-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 20px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 